/**
 * Created by pankajmishra on 25/01/15.
 */
define(['jquery','mustache','module/home/showUpdateBox'], function($, Mustache, showUpdateBox){

    var template = require('module/template/homeTemplate'), optionDom, selectDom;

    var getOption = function (i){
        return $(Mustache.render( template['vote-option'], {index:i+1}));
    };

    var createOptionBox =  function(n, dom){
        dom.empty();
        for(var i=0;i<n;++i){
            dom.append(getOption(i));
        }
    };

    var chooseOption = function(){

        if($(this).val() == 0){
            return;
        }
        createOptionBox($(this).val(), optionDom);
    };

    var render = function(){
       // $('.main-content').empty();

        var vote = $(template['vote-home']), dom = $(template['vote-agenda']);
        $('.main-content').prepend(vote);
        selectDom = dom.find('.options select');
        selectDom.once('change',chooseOption);
        optionDom = dom.find('.genOption');
        showUpdateBox($("#updateInput"), {updateType : '1', addTitle: true,
            addAgenda : {dom: dom,getValue : value, isValid: valid}});
    };


    var valid = function(){
        if(selectDom.val() == 0){
            return false;
        }
        var valid = true;
        $.each(optionDom.find('input[type="text"]'), function(index, dom){
            if($(dom).val().trim().length == 0){
                valid = false;
            }
        });
        return valid;
    };

    var value = function(){
        var value = [];
        $.each(optionDom.find('input[type="text"]'), function(index, dom){
            value.push({index:index, title:$(dom).val(), resp_count : 0});
        });
        return JSON.stringify({options:value});
    };

    return {
        render : render,
        getValue : value
    }

});